<?php

namespace App\Modules\User\Services;
use  App\Modules\User\Models\User;
use Illuminate\Support\Facades\Log;
use JWTAuth;
use JWTFactory;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Support\Facades\DB;

class UserService
{

    static function getInfoFromToken(){
        try{

            $token = JWTAuth::parseToken()->authenticate();
//             Log::info('getInfoFromToken_token:'.json_encode($token));
            if($token)  $token =$token->toArray();
            return $token;

        }catch (TokenExpiredException $e){

            throw new \Exception('Token has expired',10080);

        }catch (TokenInvalidException $e){

            throw new \Exception('Token is invalid',10081);
        }
    }

    static function idEncode($uid){
        $hashids = new \Hashids\Hashids('',16,'abcdefghjklmnopqrstuvwxyz1234567890');
        return $hashids->encode($uid);
    }

    static function idDecode($code){
        $hashids = new \Hashids\Hashids('',16,'abcdefghjklmnopqrstuvwxyz1234567890');
        $res = $hashids->decode($code);
        if($res && isset($res[0])){
            return $res[0];
        }
        return null;
    }

    /**
     * 获取用户简单信息
     * @param $uid
     * @return array
     */
    static function getUserProfile($uid){
        $userInfo = User::getUserInfo($uid);
        if(!$userInfo){
           return false;
        }
        $userInfo = $userInfo->toArray();
        $is_auth =1;
        if(empty($userInfo['nickname']) && empty($userInfo['head_img'])){
            $is_auth=0;
        }
        $nickname = $userInfo['nickname']?$userInfo['nickname']:substr(md5($userInfo['id']),0,10);
        $avatarUrl = $userInfo['head_img']?$userInfo['head_img']:env('DEFAULT_AVATAR');
        $id = $userInfo['id'];
        return [
            'nickname'=>$nickname,
            'avatarUrl'=>$avatarUrl,
            'id'=>$id,
            'is_auth'=>$is_auth
        ];
    }

    /**
     * 以手机号获取用户
     * @param $phone
     * @return mixed
     */
    public static function getUserInfoByPhone($phone){
        return User::where('phone',$phone)->where('status',1)->first();
    }

    public static function deleteOne($uid) {
        return User::where('id',$uid)->delete();
    }

    static function getById($id) {
        return User::find($id);
    }

    /**
     * 个人健康档案
     */
    public static function updateUser($data){
        return User::updateUser($data);
    }

    /**
     * 修改用户金币
     */
    public static function updateCoin($user_id,$coin){
        return DB::table('users')->where('id',$user_id)->increment('balance',$coin);
    }
}